package com.xzy.learn.spring.bean.definition;

import com.xzy.learn.spring.entity.User;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.GenericBeanDefinition;

/**
 * {@link org.springframework.beans.factory.config.BeanDefinition} 构建示例
 *
 * @author xzy.xiao
 * @date 2022/5/30  15:10
 */
public class BeanDefinitionCreationDemo {
    public static void main(String[] args) {
        BeanDefinition beanDefinition1 = buildBeanDefinitionByGenericBeanDefinition();
        BeanDefinition beanDefinition2 = buildBeanDefinitionByBeanDefinitionBuilder();

        System.out.println(beanDefinition1);
        System.out.println(beanDefinition2);
    }

    /**
     * 定义 {@code BeanDefinition}：通过 {@code GenericBeanDefinition}
     */
    public static GenericBeanDefinition buildBeanDefinitionByGenericBeanDefinition() {
        GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
        // 类型
        genericBeanDefinition.setBeanClass(User.class);
        // 属性
        MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues
                .add("id", 1L)
                .add("name", "张三");
        genericBeanDefinition.setPropertyValues(propertyValues);

        return genericBeanDefinition;
    }

    /**
     * 定义 {@code BeanDefinition}：通过 {@code BeanDefinitionBuilder}
     */
    public static AbstractBeanDefinition buildBeanDefinitionByBeanDefinitionBuilder() {
        // 类型
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        // 属性
        beanDefinitionBuilder
                .addPropertyValue("id", 1L)
                .addPropertyValue("name", "张三");

        AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();

        return beanDefinition;
    }
}
